<template>
    <div style="height: 100%" class="warp-2 body-content">
        <navbar :title="$t('circle_kg_1')">
            <template #right>
                <a class="add-btn" :class="{'add-ok' : kgData.wctName.length > 0 && kgData.wctDesc.length > 0}" @click="saveOrUpdateTeam">
                {{ $t('sure') }}
            </a>
            </template>
        </navbar>
        <div class="content-noBottom">
            <div class="add-body">
                <div class="add-item">
                    <div>{{ $t('circle_kg_8') }}</div>
                    <div class="add-input">
                        <van-field v-model="kgData.wctName" :placeholder="$t('circle_kg_60')" maxlength="10" show-word-limit />
                    </div>
                </div>
                <div class="add-item">
                    <div>{{ $t('circle_kg_9') }}</div>
                    <div class="add-input">
                        <van-uploader v-model="fileList" multiple :max-count="1" :after-read="upload"/>
                    </div>
                </div>
                <div class="add-item">
                    <div>{{ $t('circle_kg_10') }}</div>
                    <div class="add-input">
                        <van-field v-model="kgData.wctDesc" type="textarea" :placeholder="$t('circle_kg_61')" maxlength="50" show-word-limit />
                    </div>
                </div>
                <div class="add-item">
                    <div class="item-handle">
                        <div>{{ $t('circle_kg_11') }}</div>
                        <div><van-button icon="plus" type="primary" size="mini" @click="showMemberBox">{{ $t('circle_kg_12') }}</van-button></div>
                    </div>
                    <div class="add-input">
                        <div class="member-list">
                            <van-tag closeable size="medium" v-for="(item, index) in kgData.members" :key="item.wcmEntId || item.tmEntId" type="primary" @close="closeSelectMember(index)" class="tag-px">
                                <span @click.stop="setAdmin(item)" style="display: flex;align-items: center"><van-icon name="friends" v-show="item.tmRole === 'MANAGER' || item.tmRole === 'T_MANAGER'"/> {{ item.wcmName || item.memberName }}</span>
                            </van-tag>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- <van-overlay :show="isShowMemberBox" @click="isShowMemberBox = false">
            <div class="member-box" @click.stop>
                <div class="box-border">
                    <div class="box-title">
                        <div><a @click="isShowMemberBox = false">{{ $t('circle_kg_13') }}</a></div>
                        <div>{{ $t('circle_kg_12') }}</div>
                        <div><a :class="{'btn-class': selectUserList.length > 0}" @click="okSelectMember">{{ $t('circle_kg_14') }}</a></div>
                    </div>
                    <div>
                        <van-search v-model="search" @search="searchUser" :placeholder="$t('circle_kg_15')" />
                    </div>
                    <div class="box-item-list">
                        <van-loading v-if="isLoading" size="50px"/>
                        <van-checkbox-group v-model="selectUserList">
                            <div class="box-item" v-for="(item, index) in circleMemberList" :key="item.wcmEntId" @click="selectCheckBox(item, index)">
                                <div><van-checkbox :name="item.wcmEntId"></van-checkbox></div>
                                <div>{{ item.wcmName }}</div>
                            </div>
                        </van-checkbox-group>
                    </div>
                </div>
            </div>
        </van-overlay> -->
        <van-popup v-model="isShowMemberBox" position="bottom" :overlay="true">
            <div class="box-border">
                    <div class="box-title">
                        <div><a @click="isShowMemberBox = false">{{ $t('circle_kg_13') }}</a></div>
                        <div>{{ $t('circle_kg_12') }}</div>
                        <div><a :class="{'btn-class': selectUserList.length > 0}" @click="okSelectMember">{{ $t('circle_kg_14') }}</a></div>
                    </div>
                    <div>
                        <van-search v-model="search" @search="searchUser" :placeholder="$t('circle_kg_15')" />
                    </div>
                    <div class="box-item-list">
                        <van-loading v-if="isLoading" size="50px"/>
                        <van-checkbox-group v-model="selectUserList">
                            <div class="box-item" v-for="(item, index) in circleMemberList" :key="item.wcmEntId" @click="selectCheckBox(item, index)">
                                <div><van-checkbox :name="item.wcmEntId"></van-checkbox></div>
                                <div>{{ item.wcmName }}</div>
                            </div>
                        </van-checkbox-group>
                    </div>
                </div>
        </van-popup>
    </div>
</template>

<script>
import { Uploader, Toast, Field, Tag, Overlay, Button, Search, Checkbox, CheckboxGroup, Loading, Icon } from 'vant';
import team from '../../../../static/images/team.png';
import {cwnEncrypt, cwnDecrypt} from '@/utils/tools';
export default {
    name: 'AddTeam',
    components: {
        vanUploader: Uploader,
        vanToast: Toast,
        vanField: Field,
        vanTag: Tag,
        vanOverlay: Overlay,
        vanButton: Button,
        vanSearch: Search,
        vanCheckbox: Checkbox,
        vanCheckboxGroup: CheckboxGroup,
        vanLoading: Loading,
        vanIcon: Icon
    },
    data() {
        return {
            fileList: [],
            kgData: {
                wctName: '',
                wctDesc: '',
                members: [],
                wctWcId: -1,
                wctImage: '',
                wctIsDefultImg: true
            },
            isShowMemberBox: false,
            search: '',
            selectUserList: [],
            selectUserMap: new Map(),
            circleMemberList: [],
            oldCircleMemberList: [],
            isLoading: false,
            teamPng: team
        };
    },
    methods: {
        ...{cwnEncrypt, cwnDecrypt},
        searchUser() {
            this.circleMemberList = this.oldCircleMemberList.filter(item => {
                if (item.wcmName.includes(this.search)) {
                    return item;
                }
            });
        },
        setAdmin(data) {
            if (data.tmRole && (data.tmRole === 'MANAGER' || data.tmRole === 'T_MANAGER')) {
                this.$set(data, 'tmRole', 'MEMBER');
            } else {
                this.$set(data, 'tmRole', 'MANAGER');
            }
        },
        saveOrUpdateTeam() {
            if (this.kgData.wctId) {
                this.$axios.put(`/app/api/trainee/work-circle/team/${this.kgData.wctWcId}`, this.dataHandle()).then(res => {
                    Toast({message: this.$t('circle_kg_16'), forbidClick: true});
                    this.$router.go(-1);
                }).catch(res => {
                    // Toast({message: this.$t('circle_kg_18'), forbidClick: true});
                    Toast({message: res.response.data.errMsg, forbidClick: true});
                });
            } else {
                if (this.kgData.wctName.length > 0 && this.kgData.wctDesc.length > 0) {
                    this.$axios.post(`/app/api/trainee/work-circle/team/${this.kgData.wctWcId}`, this.dataHandle()).then(res => {
                        Toast({message: this.$t('circle_kg_17'), forbidClick: true});
                        this.$router.go(-1);
                    }).catch(res => {
                        // Toast({message: this.$t('circle_kg_18'), forbidClick: true});
                        Toast({message: res.response.data.errMsg, forbidClick: true});
                    });
                } else {
                    Toast({message: this.$t('circle_kg_76'), forbidClick: true});
                }
            }
        },
        dataHandle() {
            if (this.fileList.length === 0) {
                this.kgData.wctIsDefultImg = true;
            }
            let data = Object.assign({}, this.kgData);
            if (this.kgData.members.length > 0) {
                let members = [];
                this.kgData.members.forEach(item => {
                    members.push({tmEntId: item.wcmEntId || item.tmEntId, tmRole: item.tmRole});
                });
                data.members = members;
            }
            return data;
        },
        okSelectMember() {
            if (this.selectUserList.length > 0) {
                let list = [];
                this.selectUserList.forEach((item) => {
                    for (let i = 0; i < this.circleMemberList.length; i++) {
                        if (item === this.circleMemberList[i].wcmEntId) {
                            let data = this.circleMemberList[i];
                            if (this.selectUserMap.has(item)) {
                                this.$set(data, 'tmRole', this.selectUserMap.get(item));
                            } else {
                                this.$set(data, 'tmRole', 'MEMBER');
                            }
                            list.push(data);
                            break;
                        }
                    }
                });
                this.kgData.members = list;
                this.isShowMemberBox = false;
            }
        },
        showMemberBox() {
            this.isShowMemberBox = true;
            // this.selectUserList = [].concat(this.kgData.members);
            let list = [];
            let map = new Map();
            this.kgData.members.forEach(item => {
                list.push(item.wcmEntId || item.tmEntId);
                map.set(item.wcmEntId || item.tmEntId, item.tmRole);
            });
            this.selectUserList = list;
            this.selectUserMap = map;
            if (this.circleMemberList.length === 0) {
                this.isLoading = true;
                this.$axios.get(`/app/api/trainee/work-circle/member/basis/${this.kgData.wctWcId}`).then(res => {
                    if (res.data && res.data.length > 0) {
                        this.circleMemberList = res.data;
                        this.oldCircleMemberList = [].concat(this.circleMemberList);
                    }
                    this.isLoading = false;
                });
            }
        },
        selectCheckBox(data, index) {
            let n = this.selectUserList.indexOf(data.wcmEntId);
            if (n > -1) {
                this.selectUserList.splice(n, 1);
                // this.selectUserMap.delete(data.wcmEntId);
            } else {
                this.selectUserList.push(data.wcmEntId);
                // this.selectUserMap.set(data.wcmEntId, index);
            }
        },
        closeSelectMember(index) {
            let entId = this.kgData.members[index];
            this.kgData.members.splice(index, 1);
            this.selectUserMap.delete(entId);
        },
        upload(file) {
            file.status = 'uploading';
            let formData = new FormData();
            formData.append('file', file.file);
            this.$axios.post('/app/api/file', formData).then(res => {
                this.kgData.wctImage = res.data.url;
                this.kgData.wctIsDefultImg = false;
                file.status = 'done';
            });
        },
        getKnowledgeDataByWctId(wctId) {
            this.$axios.get(`/app/api/trainee/work-circle/team/${wctId}`).then(res => {
                this.kgData = res.data;
                if (this.kgData.wctIsDefultImg) {
                    this.fileList.push({url: this.teamPng, isImage: true});
                } else {
                    this.fileList.push({url: this.appUrl + this.kgData.wctImage});
                }
                if (this.kgData.members.length > 0) {
                    this.kgData.members.forEach(item => {
                        // this.selectUserList.push({wcmEntId: item.tmEntId, wcmName: item.memberName});
                        this.selectUserList.push(item.tmEntId);
                        this.selectUserMap.set(item.tmEntId, item.tmRole);
                    });
                }
            });
        }
    },
    created() {
        let data = this.$route.query;
        if (data.wctId) {
            this.getKnowledgeDataByWctId(this.cwnDecrypt(data.wctId));
        } else {
            this.kgData.wctWcId = this.cwnDecrypt(data.wctWcId);
            if (!data.wctImage) {
                this.fileList.push({url: this.teamPng, isImage: true});
            }
        }
    },
    watch: {
        search() {
            if (this.search === null || this.search === '' || this.search.length === 0) {
                this.circleMemberList = [].concat(this.oldCircleMemberList);
            }
        }
    }
};
</script>

<style scoped lang="less">
    /deep/.van-overlay {
        z-index: 999;
    }
    // .member-box {
    //     background: #fff;
    //     position: absolute;
    //     bottom: 0;
    //     width: 100%;
    //     max-height: 600px;
    //     border-radius: 16px 16px 0 0;
        .box-border {
            padding: 0 15px;
            .box-title {
                height: 48px;
                display: flex;
                align-items: center;
                &>div:first-child{
                    flex: 1;
                    &>a {
                        padding-right: 10px;
                    }
                }
                &>div:last-child {
                    flex: 1;
                    text-align: right;
                    &>a {
                        padding-left: 10px;
                        color: #ACACAC;
                    }
                }
                &>div:nth-child(2) {
                    flex: 2;
                    text-align: center;
                }
                .btn-class {
                    color: #000 !important;
                }
            }
            /deep/.van-search {
                padding: 0 0 10px 0;
            }
            .box-item-list {
                overflow-y: auto;
                max-height: 400px;
                /deep/.van-loading {
                    text-align: center;
                }
                .box-item {
                    display: flex;
                    align-items: center;
                    height: 50px;
                    &>div:first-child {
                        width: 50px;
                    }
                    &>div:last-child {
                        flex-grow: 1;
                    }
                }
            }
        }
    // }
    .add-body {
        height: 100%;
        overflow-y: auto;
        .add-item {
            margin-bottom: 15px;
            .item-handle {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            &:first-child {
                margin-top: 15px;
            }
            &>div:first-child {
                margin-bottom: 5px;
                padding: 0 10px;
            }
            .add-input {
                padding: 20px 10px;
                background: #fff;
                display: flex;
                align-content: center;
                justify-content: space-between;
                /deep/.van-cell {
                    padding: 0;
                }
                .member-list {
                    // display: flex;
                    .tag-px {
                        margin-right: 5px;
                        margin-bottom: 5px;
                    }
                }
            }
        }
    }
    .overwrite-title {
        display: flex;
        align-content: center;
        justify-content: center;
        height: 55px;
        line-height: 55px;
        font-size: 18px;
        color: #333;
    }
    .add-btn {
        height: 55px;
        line-height: 55px;
        padding: 0 15px;
        font-size: 16px;
        color: #ccc;
    }
    .add-ok {
        color: #1a1a1a !important;
    }
</style>
